package com.sq.partner.manager.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.ActirationErrorInfo;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.ActirationApplyCardExcel;
import com.sq.partner.manager.mybatis.model.ActirationCardApply;
import com.sq.partner.manager.mybatis.model.ActirationCardDifinition;
import com.sq.partner.manager.mybatis.model.ActirationCardResultDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.ActirationCardApplyService;
import com.sq.partner.manager.service.ActirationCardPowerService;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 激活卡申请及审批
 * SQ
 *
 */
@SuppressWarnings("deprecation")
@Controller
@RequestMapping(value = "/actirationCardApply")
public class ActirationCardApplyController {
	@Resource
	private ActirationCardApplyService actirationCardApplyService;
	@Resource
	private ActirationCardPowerService powerService;
	/**
	 * 激活卡申请审批页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approval")
	public String approvalCard() throws Exception {
		return "actirationCard/activationApply/activationApproval";
	}
	@RequestMapping(value = "/add")
	public String addApprovalCard(ModelMap model,HttpServletRequest request,String id) throws Exception {
		return "actirationCard/activationApply/add";
	}
	/**
	 * 新增激活卡申请记录
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	@ResponseBody
	public Result apply(HttpSession session,ActirationCardApply applyInfo) throws Exception {
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//用户权限校验
		if(StrUtil.isNotEmpty(gatewayuser.getUserPower())&&powerService.checkPower(gatewayuser.getUserPower(), Constants.ACTIR_CARD_POWER_APPLY)){
			boolean flag=actirationCardApplyService.addApplyInfo(applyInfo,gatewayuser);
			if(flag){
				return Result.success(ActirationErrorInfo.APPLY_1);
			}else{
				return Result.error(ActirationErrorInfo.APPLY_2);
			}
		}else{
			return Result.error(ActirationErrorInfo.USER_10);
		}
	}
	/**
	 * 删除激活申请记录
	 * @param request
	 * @param applyid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteapply", method = RequestMethod.POST)
	@ResponseBody
	public Result deleteApply(HttpServletRequest request,String applyid) throws Exception {
		if(StrUtil.isNotEmpty(applyid)){
			boolean flag=actirationCardApplyService.deleteApplyInfo(applyid);
			if(flag){
				return Result.success(ActirationErrorInfo.APPLY_3);
			}else{
				return Result.error(ActirationErrorInfo.APPLY_4);
			}
		}else{
			return Result.error(ActirationErrorInfo.APPLY_5);
		}
	}
	/**
	 * 审核申请（复核，复核通过，复核打回，核准，核准通过，核准打回）
	 * @param session
	 * @param auditType 0复核1核准
	 * @param applyid
	 * @param yn	0不通过1通过
	 * @param message 说明
	 * @return
	 * @throws Exception
	 */
	 
	@RequestMapping(value = "/auditapply", method = RequestMethod.POST)
	@ResponseBody
	public Result auditApply(HttpSession session,String auditType,String applyid,String yn,String message) throws Exception {
		//获取当前登录机构
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//必须字段校验
		if(StrUtil.isNotEmpty(auditType)&&StrUtil.isNotEmpty(applyid)){
			ActirationCardResultDto flag=actirationCardApplyService.auditApplyInfo(gatewayuser,auditType,applyid,yn,message);
			if(flag.isSuccess()){
				return Result.success(ActirationErrorInfo.APPLY_6);
			}else{
				return Result.error(ActirationErrorInfo.APPLY_7+flag.getMessage());
			}
		}else{
			return Result.error(ActirationErrorInfo.APPLY_13);
		}
	}
	/**
	 * 查询一条申请详细信息
	 * @param request
	 * @param applyid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryapply", method = RequestMethod.POST)
	@ResponseBody
	public ActirationCardApply queryApply(String applyid) throws Exception {
		if(null!=applyid&&!"".equals(applyid)){
			ActirationCardApply actirationcardapply=actirationCardApplyService.queryApplyInfo(applyid);
			return actirationcardapply;
		}else{
			return null;
		}
	}
	/**
	 * 根据条件查询申请结果
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryapplyList", method = RequestMethod.POST)
	@ResponseBody
	public Page<ActirationCardApply> queryApplyList(HttpSession session,Page<ActirationCardApply> page,ActirationCardApply actirationcardapply) throws Exception {
		//获取当前登录user
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		if(StrUtil.isNotEmpty(actirationcardapply.getCardDefineId()+"")){
		    paramMap.put("cardDefineId", actirationcardapply.getCardDefineId());  
		}
		if(StrUtil.isNotEmpty(actirationcardapply.getAppDeptno())){
	    paramMap.put("appDeptno", actirationcardapply.getAppDeptno());
		}
        if(null!=actirationcardapply.getAppDate()){
            paramMap.put("appDate", actirationcardapply.getAppDate());
        }
        if(StrUtil.isNotEmpty(actirationcardapply.getStatus())){
            paramMap.put("status", actirationcardapply.getStatus());
        }
        if(StrUtil.isNotEmpty(actirationcardapply.getCardDefineName())){
            paramMap.put("cardDefineName", "%" + actirationcardapply
                    .getCardDefineName() + "%");
        }
        if(StrUtil.isNotEmpty(actirationcardapply.getStartTime())){
            paramMap.put("startTime", actirationcardapply.getStartTime());
        }
        if(StrUtil.isNotEmpty(actirationcardapply.getEndTime())){
            paramMap.put("endTime", actirationcardapply.getEndTime());
        }
        if(!"00".equals(gatewayuser.getUserComcode())){
	    	paramMap.put("loginDeptno", gatewayuser.getUserComcode());
	    }
	    page.setMap(paramMap);
		page=actirationCardApplyService.queryApplyInfoList(page);
		return page;
	}
	/**
	 * 根据机构查询已关联该机构的激活卡模板
	 * @param session
	 * @param page
	 * @param actirationCardDifinition
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querydefinebyregion", method = RequestMethod.POST)
	@ResponseBody
	public Page<ActirationCardDifinition>  QueryDefineListByRegion(HttpSession session, Page<ActirationCardDifinition> page,ActirationCardDifinition actirationCardDifinition) throws Exception{
		//获取当前登录user
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		//启用状态
	    paramMap.put("isBegin", Constants.ACTIR_CARD_ISBEGIN);
	    paramMap.put("id", actirationCardDifinition.getId());
	    if(StrUtil.isNotEmpty(actirationCardDifinition.getName())){
	        paramMap.put("name", actirationCardDifinition.getName() + "%");
	    }
	    //放入机构信息，查询关联该机构的激活卡模板
	    paramMap.put("depno", gatewayuser.getUserComcode());
	    page.setMap(paramMap);
	    page = actirationCardApplyService.queryDefineByRegion(page);
	    return page;
	}
	/**
	 * 导出Excel表格
	 * 
	 * @param response
	 * @param appId
	 * @param cardDefineId
	 * @param beginNo
	 * @param endNo
	 * @throws Exception
	 */
	@RequestMapping("/exportExcel")
	@ResponseBody
	public void exportCardExcel(HttpSession session,HttpServletRequest req, 
	        HttpServletResponse resp, Integer appId)throws Exception{
	    //权限校验 lfd added 20181009 start
	    GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
	    int count = 1;
        if(StrUtil.isNotEmpty(gatewayuser.getUserPower())&&powerService.checkPower(gatewayuser.getUserPower(), Constants.ACTIR_CARD_POWER_APPROVAL)){
        //权限校验 lfd added 20181009 end
            Map<String, Object> map = new HashMap<String, Object>();
    		map.put("appId", appId);
    		ActirationCardApply cardInfo = actirationCardApplyService.getCardInfo(map);
    			map.put("cardDefineId", cardInfo.getCardDefineId());
    			map.put("beginNo",cardInfo.getCardnoBegin() );
    			map.put("endNo", cardInfo.getCardnoEnd());
    			List<ActirationApplyCardExcel> list = actirationCardApplyService.queryCardApplyInfo(map);
    			String fileName = cardInfo.getAppDeptno()+"-"+cardInfo.getCardDefineName()+"-"+cardInfo.getUnitPp()+"份";
    			List<String[]> liststr = new ArrayList<String[]>();
    			for (ActirationApplyCardExcel cardExcel : list) {
    				liststr.add(new String[]{String.valueOf(count++),cardExcel.getName(),cardExcel.getCardNo(),cardExcel.getPassword(),
    				        cardExcel.getDisableDate(),cardInfo.getAppDeptno()});
    			}
    			String[][] dataList = liststr.toArray(new String[0][0]);
    			
    			String sheetName = "激活卡信息";  
    	        String titleName = "激活卡信息";    
    	        //int columnNumber = 4;  
    	        //增加序号和有效期限
    	        int columnNumber = 6;
    	        //int[] columnWidth = {30,30,20,35};  
    	        int[] columnWidth = {15,30,30,20,25,35};
    	        //加一列序号和有效期限
    	        //String[] columnName = {"卡名称","卡号","密码","归属机构"};
    	        String[] columnName = {"序号","卡名称","卡号","密码","卡单失效时间","归属机构"}; 
    	        	HSSFWorkbook wb = new HSSFWorkbook();
    	        	HSSFSheet sheet = wb.createSheet(sheetName);
    	        	for (int i = 0; i < columnNumber; i++){
    	            	for (int j = 0; j <= i; j++){  
    	                    if (i == j){  
    	                        sheet.setColumnWidth(i, columnWidth[j] * 256);  
    	                    }  
    	                }  
    	            }  
    	            HSSFRow row1 = sheet.createRow((int) 0);  
    	            row1.setHeightInPoints(50);
    	            HSSFDataFormat createDataFormat = wb.createDataFormat();
    	            HSSFCellStyle style2 = wb.createCellStyle();
    	            style2.setDataFormat(createDataFormat.getFormat("@"));
    	            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
    	            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
    	            style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);  
    	            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
    	            HSSFFont headerFont1 = (HSSFFont) wb.createFont();
    	            headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    	            headerFont1.setFontName("宋体");
    	            headerFont1.setFontHeightInPoints((short) 15);  
    	            style2.setFont(headerFont1);
    	            HSSFCell cell1 = row1.createCell(0); 
    	            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,columnNumber - 1)); 
    	            cell1.setCellValue(titleName);
    	            cell1.setCellStyle(style2);
    	            // 第1行
    	            HSSFRow row = sheet.createRow((int) 1);
    	            // 表头高度  
    	            row.setHeightInPoints(37);
    	            // 表头单元格样式 以及表头的字体样式  
    	            HSSFCellStyle style = wb.createCellStyle();
    	            // 自动换行 
    	            style.setWrapText(true);
    	            // 居中格式
    	            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
    	            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);    
    	            style.setBottomBorderColor(HSSFColor.BLACK.index);  
    	            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
    	            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
    	            style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
    	            style.setBorderTop(HSSFCellStyle.BORDER_THIN);    
    	            HSSFFont headerFont = (HSSFFont) wb.createFont();
    	            // 字体加粗
    	            headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    	            // 设置字体类型
    	            headerFont.setFontName("宋体");
    	            // 设置字体大小 
    	            headerFont.setFontHeightInPoints((short) 10);
    	            // 为标题样式设置字体样式 
    	            style.setFont(headerFont);
    	            HSSFCell cell = null;
    	            for (int i = 0; i < columnNumber; i++)   
    	            {  
    	            	cell = row.createCell(i);  
    	                cell.setCellValue(columnName[i]);
    	                cell.setCellStyle(style);
    	            }
    	            //创建单元格 
                    // 为数据内容设置特点新单元格样式1 自动换行 上下居中  
                    HSSFCellStyle cellStyle = wb.createCellStyle();  
                    cellStyle.setWrapText(true);// 设置自动换行  
                    cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式  
                    // 设置边框  
                    cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);  
                    cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
                    cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
                    cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
                    cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
                    HSSFCellStyle cellStyle1 = wb.createCellStyle();  
                    cellStyle1.setWrapText(true);// 设置自动换行  
                    cellStyle1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式  
                    cellStyle1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
                    // 设置边框  
                    cellStyle1.setBottomBorderColor(HSSFColor.BLACK.index);  
                    cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
                    cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
                    cellStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);  
                    cellStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);
                    cellStyle1.setDataFormat(createDataFormat.getFormat("@"));
    	            for (int i = 0; i < dataList.length; i++)   
    	            {  
    	                row = sheet.createRow((int) i + 2);    
    	                HSSFCell datacell = null;  
    	                for (int j = 0; j < columnNumber; j++){  
    	                    datacell = row.createCell(j);  
    	                    datacell.setCellValue(dataList[i][j]);  
    	                    datacell.setCellStyle(cellStyle1);  
    	                }  
    	            }  
    	            resp.setContentType("application/ms-excel;charset=UTF-8");  
    	            //解决文件名乱码（浏览器兼容问题）
    	            //resp.setHeader("Content-Disposition","attachment;filename="+ new String(fileName.getBytes(),"iso-8859-1")+".xls");
    	            String userAgent = req.getHeader("user-agent").toLowerCase();  
    	            if (userAgent.contains("msie") || userAgent.contains("trident")
    	                    || userAgent.contains("edge")) {
    	                //IE浏览器
    	                fileName = URLEncoder.encode(fileName, "UTF-8");
    	            } else {
    	                //非IE浏览器
    	                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
    	            }
    	            resp.setHeader("Content-Disposition","attachment;filename="+ fileName +".xls");
    	            OutputStream out = resp.getOutputStream();  
    	            try {
    	            	wb.write(out); 
    	            } catch (Exception e) {
    	            	e.printStackTrace();  
    	            } finally {
    	            	out.close();  
    	            }  
    	}
	} 
}
